/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.youan.log.modules.statistical.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youan.log.modules.audit.entity.EventRuleNum;
import com.youan.log.modules.audit.service.IEventRulenumService;
import com.youan.log.modules.statistical.entity.LogStatistical;
import com.youan.log.modules.statistical.mapper.LogStatisticalMapper;
import com.youan.log.modules.statistical.service.ILogStatisticalService;
import com.youan.log.modules.statistical.vo.Cascader;
import com.youan.log.modules.statistical.vo.LogStatisticalVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 *  服务实现类
 *
 * @author BladeX
 * @since 2021-03-05
 */
@Service
@Slf4j
public class LogStatisticalServiceImpl extends ServiceImpl<LogStatisticalMapper, LogStatistical> implements ILogStatisticalService {

	@Autowired
	private IEventRulenumService eventRulenumService;
	@Autowired
	private LogStatisticalMapper logStatisticalMapper;

	@Override
	public IPage<LogStatisticalVO> selectLogStatisticalPage(IPage<LogStatisticalVO> page, LogStatisticalVO logStatistical) {
		return page.setRecords(baseMapper.selectLogStatisticalPage(page, logStatistical));
	}

	@Override
	public IPage<LogStatisticalVO> statistics(IPage<LogStatisticalVO> page, LogStatisticalVO logStatistical, String groupByList) {
		return getLogStatisticalVOIPage(page, logStatistical, groupByList, null);
	}

	@Override
	public IPage<LogStatisticalVO> statisticsForLoginError(IPage<LogStatisticalVO> page, LogStatisticalVO logStatistical, String groupByList) throws Exception {
		LambdaQueryWrapper<EventRuleNum> eventRuleNumLqw = new LambdaQueryWrapper<EventRuleNum>()
				.eq(EventRuleNum::getRuleName, "mysql_登录失败");
		EventRuleNum eventRuleNum = eventRulenumService.getOne(eventRuleNumLqw);
		if(eventRuleNum == null) {
			log.error("时间：" + LocalDateTime.now() + "，错误信息：不存在mysql_登录失败的事件类型！");
			throw new Exception("不存在mysql_登录失败的事件类型！");
		}
		logStatistical.setIssueType(eventRuleNum.getRuleId());
		logStatistical.getRuleList().add(eventRuleNum.getRuleId());
		return getLogStatisticalVOIPage(page, logStatistical, groupByList,"mysql_登录失败");
	}

	@Override
	public List<Cascader> getCountryCascader() {
		// 获取所有国家
		List<Cascader> countryList = logStatisticalMapper.getAllCountry();
		for (Cascader country : countryList) {
			country.setValue(country.getLabel()); // label 和 value 一样，不在数据库层直接设置是因为速度太慢
		}
		return countryList;
	}

	@Override
	public List<Cascader> getProvinceByCountry(String country) {
		// 根据国家获取所有属于这个国家的省份
		List<Cascader> provinceList = logStatisticalMapper.getProvinceByCountry(country);
		for (Cascader province : provinceList) {
			province.setValue(province.getLabel());
		}
		return provinceList;
	}

	@Override
	public List<Cascader> getCityByProvince(String province) {
		// 根据省份获取城市
		List<Cascader> cityList = logStatisticalMapper.getCityByProvince(province);
		for (Cascader city : cityList) {
			city.setValue(city.getLabel());
		}
		return cityList;
	}

	private IPage<LogStatisticalVO> getLogStatisticalVOIPage(IPage<LogStatisticalVO> page, LogStatisticalVO logStatistical, String groupByList, String ruleName) {
		if(StringUtils.isNotBlank(logStatistical.getRuleIds())) {
			logStatistical.setRuleList(Arrays.asList(logStatistical.getRuleIds().split(",")));
		}
		List<LogStatisticalVO> list = baseMapper.statistics(page, logStatistical, groupByList);
		if(CollectionUtil.isNotEmpty(list)) {
			list.forEach(item -> {
				if(StringUtils.isNotBlank(item.getIssueType())) {
					LambdaQueryWrapper<EventRuleNum> eventRuleNumLqw = new LambdaQueryWrapper<EventRuleNum>()
							.eq(EventRuleNum::getRuleId, item.getIssueType());
					EventRuleNum eventRuleNum = eventRulenumService.getOne(eventRuleNumLqw);
					if(eventRuleNum != null) {
						item.setIssueTypeName(eventRuleNum.getRuleName());
					}
				}else if(StringUtils.isNotBlank(ruleName)) {
					item.setIssueTypeName(ruleName);
				}

				if(StringUtils.isNotBlank(item.getVisitDirection())) {
					item.setDirectionName(item.getVisitDirection().equals("s")?"源ip归属山东":"目的ip归属山东");
				}
				// 如果是空的话，可能是专门某一种错误的查询，这里设置为该规则
				if(StringUtils.isBlank(item.getIssueType())) {
					item.setIssueType(logStatistical.getIssueType());
				}
			});
		}
		return page.setRecords(list);
	}

}
